package com.awesome.kotlindemo.base

import android.content.ComponentCallbacks
import android.content.res.Configuration
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import com.awesome.common.util.log.ShowLogUtil
import com.awesome.kotlindemo.R

/**
 * 今日头条屏幕适配
 */
class AutoSizeActivity : AppCompatActivity() {
    private var density = 0f
    private var scaledDensity = 0f

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setCustomDensity()
        setContentView(R.layout.activity_auto_size)
        val textView = findViewById<TextView>(R.id.tv)
        textView.postDelayed({
            ShowLogUtil.info("textView.width=" + textView.width)
        }, 1000)
    }

    protected open fun setCustomDensity() {
        val displayMetrics = application.resources.displayMetrics
        if (density == 0f) {
            density = displayMetrics.density
            scaledDensity = displayMetrics.scaledDensity
            // 监听切换字体
            application.registerComponentCallbacks(object : ComponentCallbacks {
                override fun onConfigurationChanged(newConfig: Configuration) {
                    if (newConfig.fontScale > 0) {
                        scaledDensity = application.resources.displayMetrics.scaledDensity
                    }
                }

                override fun onLowMemory() {}
            })
        }
        // 以 360dp 的设计图为标准
        val targetDensity = (displayMetrics.widthPixels / 360).toFloat()
        val targetScaledDensity = targetDensity * (scaledDensity / density)
        val targetDensityDpi = (160 * targetDensity).toInt()
        displayMetrics.density = targetDensity
        displayMetrics.scaledDensity = targetScaledDensity
        displayMetrics.densityDpi = targetDensityDpi
        val activityDisplayMetrics = resources.displayMetrics
        activityDisplayMetrics.density = targetDensity
        activityDisplayMetrics.scaledDensity = targetScaledDensity
        activityDisplayMetrics.densityDpi = targetDensityDpi
    }
}